package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-28
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 校验管理员账户信息；生成令牌；响应登录结果
     *
     * @param dto
     * @return 业务数据：data:{user:{},token:""}
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.登录信息非空判断
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断管理员认证信息是否合法
        //2.1 根据账户名称查询账户信息
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, dto.getName());
        AdUser one = this.getOne(queryWrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!one.getStatus().equals(9)) {
            return ResponseResult.errorResult(400, "账号被锁定了");
        }
        //2.2 判断密码是否正确
        String pwdStr = dto.getPassword() + one.getSalt();
        String pwdEncodedStr = DigestUtils.md5DigestAsHex(pwdStr.getBytes());
        if (!pwdEncodedStr.equals(one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3.生成令牌-JWT令牌载荷中包含用户信息
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId", one.getId());
        claimMaps.put("userName", one.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        //4.响应业务数据 data:{user:{},token:""}
        HashMap<String, Object> mapResult = new HashMap<>();
        //用户信息进行脱敏处理
        one.setPassword(null);
        one.setPhone(null);
        one.setSalt(null);
        mapResult.put("user", one);
        mapResult.put("token", token);
        return ResponseResult.okResult(mapResult);
    }
}
